package echecs;

import position.Position;
import position.PositionFabrique;
import position.PositionFabrique.PositionType;
import echecs.Pieces.Piece;
import java.util.List;
import static echecs.Pieces.Piece.*;

public class CoupsLegaux extends Etat {

    private List<Coups> pListeCoupsLegaux;
    private List<Coups> pListeCoups;

    public CoupsLegaux() {
        Position position = PositionFabrique.creerPosition(PositionType.INITIALE);
        position.placerPieces();
        Algorithme algo = new Algorithme(Couleur.BLANC, position.getPieces());
        pListeCoups = algo.getPListeCoups();
        pListeCoupsLegaux = examineEchecs(algo);


        System.out.print(toString());
    }

    private List<Coups> examineEchecs(Algorithme algo) {
        //private void roque_possible
        //private void enEchecs
        int index_roi = 0;
        Couleur pCouleurQuiNeJouePas;

        if (algo._couleur == Couleur.BLANC) {
            pCouleurQuiNeJouePas = Couleur.NOIR;
            while (algo.PIECES[index_roi] != ROI_BLANC) {
                index_roi++;
            }
        } else {
            pCouleurQuiNeJouePas = Couleur.BLANC;
            index_roi = 0;
            while (algo.PIECES[index_roi] != ROI_NOIR) {
                index_roi++;
            }
        }
        Piece[] copyPIECES;
        List<Coups> listeCoupsAdverses;
//        System.out.print("(ROI en " + Case.valeur(index) + ")");
        for (Coups coups : pListeCoups) {
            copyPIECES = new Piece[NB_COLONNES * NB_RANGEES];
            System.arraycopy(algo.PIECES, 0, copyPIECES, 0, NB_COLONNES * NB_RANGEES);
            copyPIECES = simulerUnCoups(coups.pIndexDepart, coups.pIndexArrivee, copyPIECES);

            listeCoupsAdverses = new Algorithme(pCouleurQuiNeJouePas, copyPIECES).getPListeCoups();

            for (Coups cps : listeCoupsAdverses) {

                if (cps.pIndexArrivee == index_roi) {
                    pListeCoups.remove(coups);
                }
                System.out.print(cps.pPieceDepart.toString() + "(" + Case.valeur(cps.pIndexDepart) + ") :" +
                        Case.valeur(cps.pIndexArrivee) + '\n');

            }
            System.out.println();

        }
        return pListeCoups;
    }

    private Piece[] simulerUnCoups(int pIndexDepart, int pIndexArrivee, Piece[] pCopyPIECES) {
        pCopyPIECES[pIndexArrivee] = pCopyPIECES[pIndexDepart];
        pCopyPIECES[pIndexDepart] = null;
        return pCopyPIECES;
    }

    @Override
    public String toString() {
        super.toString();
        String ret = "";
        for (Coups coups : pListeCoupsLegaux) {
            ret += coups.pPieceDepart.toString() + "(" + Case.valeur(coups.pIndexDepart) + ") :" +
                    Case.valeur(coups.pIndexArrivee) + '\n';

        }
        return ret;
    }
}
